package com.tiger.project.service.impl;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.lang.hash.Hash;
import com.tiger.common.core.domain.entity.SysDept;
import com.tiger.common.core.domain.entity.SysUser;
import com.tiger.system.service.ISysDeptService;
import com.tiger.system.service.ISysUserService;
import com.tiger.weixin.api.WeixinApi;
import com.tiger.weixin.config.WxProperties;
import com.tiger.weixin.dto.WxMsgTask;
import okhttp3.*;
import com.alibaba.fastjson2.JSONObject;
import com.tiger.common.core.domain.model.LoginUser;
import com.tiger.common.utils.DateUtils;
import com.tiger.common.utils.StringUtils;
import com.tiger.common.utils.file.FileUtils;
import com.tiger.project.domain.*;
import com.tiger.project.mapper.*;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import com.tiger.project.service.IOainfoService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * OA消息待办已办Service业务层处理
 *
 * @author iot
 * @date 2022-12-13
 */
@Service
@Slf4j
public class OainfoServiceImpl implements IOainfoService {

    @Autowired
    private OainfoMapper oainfoMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private WeixinApi weixinApi;
    @Autowired
    private WxProperties wxProperties;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询OA消息待办已办
     *
     * @param id OA消息待办已办主键
     * @return OA消息待办已办
     */
    @Override
    public Oainfo selectOainfoById(Long id) {
        return oainfoMapper.selectOainfoById(id);
    }

    /**
     * 查询OA消息待办已办列表
     *
     * @param oainfo OA消息待办已办
     * @return OA消息待办已办
     */
    @Override
    public List<Oainfo> selectOainfoList(Oainfo oainfo) {
        return oainfoMapper.selectOainfoList(oainfo);
    }

    /**
     * 新增OA消息待办已办
     *
     * @param oainfo OA消息待办已办
     * @return 结果
     */
    @Override
    public int insertOainfo(Oainfo oainfo) {
        sendWxMsg(oainfo);
        return oainfoMapper.insertOainfo(oainfo);
    }

    private void sendWxMsg(Oainfo oainfo) {
        String recipientId = oainfo.getRecipientId();
        SysUser sysUser = sysUserService.selectUserByOaid(recipientId);

        if (sysUser == null || StringUtils.isBlank(sysUser.getOpenid())) {
            log.error("未找到用户信息！");
        } else {
            // todo 发送消息
            WxMsgTask wxMsgTask = new WxMsgTask(wxProperties.getMsgTemp().getTempId());
            wxMsgTask.setTouser(sysUser.getOpenid());
            HashMap<String, WxMsgTask.Data> data = new HashMap<>();
            data.put("first", new WxMsgTask.Data("您好，您有一条来自集团OA系统的待办通知"));
            SysDept sysDept = sysDeptService.selectDeptById(oainfo.getCompanyId());
            data.put("keyword1", new WxMsgTask.Data(sysDept.getDeptName()));
            data.put("keyword2", new WxMsgTask.Data(oainfo.getSponsorName()));
            data.put("keyword4", new WxMsgTask.Data(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, oainfo.getDate())));
            data.put("keyword5", new WxMsgTask.Data(oainfo.getTitle()));
            data.put("remark", new WxMsgTask.Data(""));
            wxMsgTask.setData(data);
            wxMsgTask.setUrl(oainfo.getFileAddress());
            weixinApi.sendMsg(wxMsgTask);
        }
    }

    /**
     * 修改OA消息待办已办
     *
     * @param oainfo OA消息待办已办
     * @return 结果
     */
    @Override
    public int updateOainfo(Oainfo oainfo) {
        return oainfoMapper.updateOainfo(oainfo);
    }

    /**
     * 批量删除OA消息待办已办
     *
     * @param ids 需要删除的OA消息待办已办主键
     * @return 结果
     */
    @Override
    public int deleteOainfoByIds(Long[] ids) {
        return oainfoMapper.deleteOainfoByIds(ids);
    }

    /**
     * 删除OA消息待办已办信息
     *
     * @param id OA消息待办已办主键
     * @return 结果
     */
    @Override
    public int deleteOainfoById(Long id) {
        return oainfoMapper.deleteOainfoById(id);
    }


    /**
     * 获取OA审核token
     * @param userName REST账号
     * @param passWord REST密码
     * @return
     */
    @Override
    public String getToken(String userName, String passWord,String loginName) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try{
            // 创建客户端连接对象
            httpClient = HttpClients.createDefault();
            String url = "http://www.ntgrzc.com/seeyon/rest/token/"+userName+"/"+passWord+"?loginName="+loginName;
//            System.out.println(url);
            HttpGet get = new HttpGet(url);

            // 获取返回对象
            response = httpClient.execute(get);
            System.out.println(result);

            // 整理返回值
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"utf-8");
        }catch (Exception  e){
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
                response.close();
            }catch (IOException i){
                i.printStackTrace();
            }

        }

        return result;
    }

    /**
     * 合同发起发起审核
     * @param contractSponsor 合同发起
     * @param
     * @return
     */
    @Override
    public String oaContractSponsor(ContractSponsor contractSponsor, LoginUser loginUser) throws IOException {
//        CloseableHttpClient httpClient = null;
//        CloseableHttpResponse response = null;
        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+contractSponsor.getToken();


        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");

        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "HTFQSPD1");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");

        Map<String, Object> data2 = new HashMap<String, Object>();
        HashMap<String, Object> map1 = new HashMap<>();

        //合同文本
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map2 = new HashMap<>();
        map2.put("fileUrl",contractSponsor.getFileId());
        map2.put("sort",1);
        long l = new Random().nextLong();
        map2.put("subReference",l);
        list.add(map2);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取合同发起数据
        map1.put("合同编号",contractSponsor.getContractSponsorNo());
        map1.put("合同名称",contractSponsor.getName());
        map1.put("提交日期", DateUtils.getDate());
        map1.put("合同类型",contractSponsor.getContractType());
        map1.put("出租方",contractSponsor.getLessorName());
        map1.put("承租方",contractSponsor.getLesseeName());
        map1.put("招租方式",contractSponsor.getLetWay());
        map1.put("甲方联系人",contractSponsor.getFirstParty());
        map1.put("甲方联系方式",contractSponsor.getFirstPartyPhone());
        map1.put("乙方联系人",contractSponsor.getSecondParty());
        map1.put("乙方联系方式",contractSponsor.getSecondPartyPhone());
        map1.put("开始日期", sdf.format(contractSponsor.getRentStateTime()));
        map1.put("结束日期",sdf.format(contractSponsor.getRentEndTime()));
        map1.put("付款周期",contractSponsor.getPaymentCycle());
        map1.put("年租金",contractSponsor.getYearlyRent());
        map1.put("物业费",contractSponsor.getPropertyFee());
        map1.put("押金",contractSponsor.getCashPledge());
        map1.put("所租资产",contractSponsor.getAssetName());
        map1.put("产权编号",contractSponsor.getPropertyCertification());
        map1.put("签订日期",sdf.format(contractSponsor.getSignTime()));
        map1.put("签订地点",contractSponsor.getSignPlace());
        map1.put("租赁用途",contractSponsor.getRentUse());
        map1.put("产权面积",contractSponsor.getRentArea());
        map1.put("单据ID",contractSponsor.getId());
        map1.put("发起单位ID",loginUser.getDeptId());//公司
        //发起人
        Object id = getLoginId(contractSponsor.getToken(), contractSponsor.getLoginName());
        map1.put("发起人",id);//发起人
        map1.put("合同文本",l);



        data2.put("formmain_0714", map1);

        data2.put("thirdAttachments",list);

        data1.put("data", data2);

        map.put("data", data1);

        JSONObject object = new JSONObject(map);
        System.out.println(object);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }

    @Autowired
    private ContractSponsorMapper sponsorMapper;
    /**
     * 租金减免提交审批
     * @param contractSponsorCredit 租金减免
     * @return
     */
    @Override
    public String oaContractSponsorCredit(ContractSponsorCredit contractSponsorCredit) throws IOException {
        ContractSponsor contractSponsor = sponsorMapper.selectContractSponsorById(contractSponsorCredit.getContractSponsorId());

        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+contractSponsorCredit.getToken();
        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");

        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "ZJJMSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");

        Map<String, Object> data2 = new HashMap<String, Object>();
        HashMap<String, Object> map1 = new HashMap<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取合同发起数据
        map1.put("合同编号",contractSponsor.getContractSponsorNo());
        map1.put("合同名称",contractSponsor.getName());
        map1.put("提交日期", DateUtils.getDate());
        map1.put("减免金额",contractSponsorCredit.getCreditAmount());
        map1.put("客户名称",contractSponsor.getLesseeName());
        map1.put("账期",contractSponsorCredit.getRentPeriods());
        map1.put("房屋租金",contractSponsor.getYearlyRent());
        map1.put("减免原因",contractSponsorCredit.getCreditRemark());
        map1.put("单据ID",contractSponsorCredit.getId());
        //发起人
        Object id = getLoginId(contractSponsorCredit.getToken(), contractSponsorCredit.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0025", map1);

        data1.put("data", data2);

        map.put("data", data1);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }



    /**
     *开票申请提交审核
     * @param contractBill 账单
     * @return
     */
    @Override
    public String oaContractBill(ContractBill contractBill) throws IOException {
        ContractSponsor contractSponsor = sponsorMapper.selectContractSponsorById(contractBill.getContractSponsorId());
        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+contractBill.getToken();
        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");

        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "KPSQSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");

        Map<String, Object> data2 = new HashMap<String, Object>();
        HashMap<String, Object> map1 = new HashMap<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取合同发起数据
        map1.put("合同编号",contractSponsor.getContractSponsorNo());
        map1.put("合同名称",contractSponsor.getName());
        map1.put("提交日期", DateUtils.getDate());
        map1.put("客户名称",contractSponsor.getLesseeName());
        map1.put("开票单位",contractSponsor.getLessorName());
        map1.put("开票金额",contractBill.getInvoiceAmount());
        map1.put("账期",contractBill.getRentPeriods());
        map1.put("房屋租金",contractSponsor.getYearlyRent());
        map1.put("决策依据",contractBill.getDecisionId());
        map1.put("财务开票期限",sdf.format(contractBill.getInvoiceTime()));
        map1.put("备注",contractBill.getRemark());
        map1.put("发票类型",contractBill.getIsDedicated());
        map1.put("单据ID",contractBill.getId());
        //发起人
        Object id = getLoginId(contractBill.getToken(), contractBill.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0025", map1);

        data1.put("data", data2);

        map.put("data", data1);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }


    @Autowired
    private ContractSponsorCreditMapper creditMapper;
    @Autowired
    private PayInfoMapper payInfoMapper;
    @Autowired
    private PayInfoEnclosureMapper payInfoEnclosureMapper;
    /**
     * 租金进账提交审批
     * @param contractBill 账期
     * @return
     */
    @Override
    public String oaRecord(ContractBill contractBill) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ContractSponsor contractSponsor = sponsorMapper.selectContractSponsorById(contractBill.getContractSponsorId());
        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+contractBill.getToken();

        //减免信息
        ContractSponsorCredit credit = new ContractSponsorCredit();
        credit.setBillId(contractBill.getId());
        credit.setContractSponsorId(contractBill.getContractSponsorId());
        List<ContractSponsorCredit> creditList = creditMapper.selectContractSponsorCreditList(credit);

        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");

        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "ZJJZSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");

        Map<String, Object> data2 = new HashMap<String, Object>();
        HashMap<String, Object> map1 = new HashMap<>();



        //进账缴款记录
        PayInfo payInfo = new PayInfo();
        payInfo.setBillId(contractBill.getId());
        payInfo.setPayType(1L);
        List<PayInfo> payInfoList = payInfoMapper.selectPayInfoList(payInfo);
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        ArrayList<Map<String, Object>> list1 = new ArrayList<>();
        if (StringUtils.isNotEmpty(payInfoList)){
            for (PayInfo p : payInfoList){
                Map<String, Object> map2 = new HashMap<>();
                map2.put("缴款日期",sdf.format(p.getPayTime()));
                map2.put("缴款凭证号",p.getPayNumber());
                map2.put("缴款金额",p.getPayMoney());
                map2.put("缴款备注",p.getPayRemark());
                PayInfoEnclosure enclosure = new PayInfoEnclosure();
                enclosure.setBillId(p.getBillId());
                List<PayInfoEnclosure> enclosureList = payInfoEnclosureMapper.selectPayInfoEnclosureList(enclosure);

                if (StringUtils.isNotEmpty(enclosureList)){
                    long l = new Random().nextLong();
                    for (int i = 0;enclosureList.size()-1>=i;i++){
                        //合同文本
                        Map<String, Object> map3 = new HashMap<>();
                        map3.put("fileUrl",getOaFile(enclosureList.get(i).getUrl(),contractBill.getToken()));
                        map3.put("sort",i+1);
                        map3.put("subReference",l);
                        list1.add(map3);
                    }
                    map2.put("缴款相关凭证文件",l);
                }
                list.add(map2);
            }
        }



        //获取合同发起数据
        map1.put("合同编号",contractSponsor.getContractSponsorNo());
        map1.put("合同名称",contractSponsor.getName());
        map1.put("提交日期", DateUtils.getDate());
        map1.put("客户名称",contractSponsor.getLesseeName());
        map1.put("开票单位",contractSponsor.getLessorName());
        map1.put("开票金额",contractBill.getInvoiceAmount());
        map1.put("账期",contractBill.getRentPeriods());
        map1.put("房屋租金",contractSponsor.getYearlyRent());
        if (StringUtils.isNotEmpty(creditList)){
            map1.put("减免金额",creditList.get(0).getCreditAmount());
        }
        map1.put("财务开票期限",sdf.format(contractBill.getInvoiceTime()));
        map1.put("备注",contractBill.getRemark());
        map1.put("发票类型",contractBill.getIsDedicated());
        map1.put("单据ID",contractBill.getId());
        //发起人
        Object id = getLoginId(contractBill.getToken(), contractBill.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0024", map1);
        data2.put("formson_0029",list);
        data2.put("thirdAttachments",list1);
        data1.put("data", data2);

        map.put("data", data1);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }

    @Override
    public String oaArrival(ContractBill contractBill) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ContractSponsor contractSponsor = sponsorMapper.selectContractSponsorById(contractBill.getContractSponsorId());
        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+contractBill.getToken();

        //减免信息
        ContractSponsorCredit credit = new ContractSponsorCredit();
        credit.setBillId(contractBill.getId());
        credit.setContractSponsorId(contractBill.getContractSponsorId());
        List<ContractSponsorCredit> creditList = creditMapper.selectContractSponsorCreditList(credit);

        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");

        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "ZJDZSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");

        Map<String, Object> data2 = new HashMap<String, Object>();
        HashMap<String, Object> map1 = new HashMap<>();



        //进账缴款记录
        PayInfo payInfo = new PayInfo();
        payInfo.setBillId(contractBill.getId());
        payInfo.setPayType(2L);
        List<PayInfo> payInfoList = payInfoMapper.selectPayInfoList(payInfo);
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        ArrayList<Map<String, Object>> list1 = new ArrayList<>();
        if (StringUtils.isNotEmpty(payInfoList)){
            for (PayInfo p : payInfoList){
                Map<String, Object> map2 = new HashMap<>();
                map2.put("到账日期",sdf.format(p.getPayTime()));
                map2.put("到账凭证号",p.getPayNumber());
                map2.put("到账金额",p.getPayMoney());
                map2.put("到账备注",p.getPayRemark());
                PayInfoEnclosure enclosure = new PayInfoEnclosure();
                enclosure.setBillId(p.getBillId());
                List<PayInfoEnclosure> enclosureList = payInfoEnclosureMapper.selectPayInfoEnclosureList(enclosure);

                if (StringUtils.isNotEmpty(enclosureList)){
                    long l = new Random().nextLong();
                    for (int i = 0;enclosureList.size()-1>=i;i++){
                        //合同文本
                        Map<String, Object> map3 = new HashMap<>();
                        map3.put("fileUrl",getOaFile(enclosureList.get(i).getUrl(),contractBill.getToken()));
                        map3.put("sort",i+1);
                        map3.put("subReference",l);
                        list1.add(map3);
                    }
                    map2.put("上传附件1",l);
                }
                list.add(map2);
            }
        }



        //获取合同发起数据
        map1.put("合同编号",contractSponsor.getContractSponsorNo());
        map1.put("合同名称",contractSponsor.getName());
        map1.put("提交日期", DateUtils.getDate());
        map1.put("客户名称",contractSponsor.getLesseeName());
        map1.put("开票单位",contractSponsor.getLessorName());
        map1.put("开票金额",contractBill.getInvoiceAmount());
        map1.put("账期",contractBill.getRentPeriods());
        map1.put("房屋租金",contractSponsor.getYearlyRent());
        if (StringUtils.isNotEmpty(creditList)){
            map1.put("减免金额",creditList.get(0).getCreditAmount());
        }
        map1.put("财务开票期限",sdf.format(contractBill.getInvoiceTime()));
        map1.put("备注",contractBill.getRemark());
        map1.put("发票类型",contractBill.getIsDedicated());
        map1.put("单据ID",contractBill.getId());
        //发起人
        Object id = getLoginId(contractBill.getToken(), contractBill.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0026", map1);
        data2.put("formson_0030",list);
        data2.put("thirdAttachments",list1);
        data1.put("data", data2);

        map.put("data", data1);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }


    /**
     * 押金变更提交审核
     * @param contractSponsor 合同发起
     * @return
     */
    @Override
    public String oaDepositChange(ContractSponsor contractSponsor) throws IOException {
        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+contractSponsor.getToken();
        ContractSponsor sponsor = sponsorMapper.selectContractSponsorById(contractSponsor.getId());

        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");

        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "YJBGSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");

        Map<String, Object> data2 = new HashMap<String, Object>();
        HashMap<String, Object> map1 = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        map1.put("合同编号",sponsor.getContractSponsorNo());
        map1.put("合同名称",sponsor.getName());
        map1.put("提交日期", DateUtils.getDate());
        map1.put("租赁开始日期", sdf.format(sponsor.getRentStateTime()));
        map1.put("租赁结束日期",sdf.format(sponsor.getRentEndTime()));
        map1.put("变更原因",contractSponsor.getDepositRemark());
        map1.put("决策依据",contractSponsor.getDepositDecisionId());
        map1.put("调整后押金",contractSponsor.getCashPledge());
        map1.put("当前押金",sponsor.getCashPledge());
        map1.put("单据ID",contractSponsor.getId());
        //发起人
        Object id = getLoginId(contractSponsor.getToken(), contractSponsor.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0027", map1);

        data1.put("data", data2);

        map.put("data", data1);

        JSONObject object = new JSONObject(map);
        System.out.println(object);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }


    /**
     * 押金收款提交审批
     * @param contractSponsor 合同发起
     * @return
     */
    @Override
    public String oaDepositPayee(ContractSponsor contractSponsor) throws IOException {
        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+contractSponsor.getToken();
        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");

        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "YJSKSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");

        Map<String, Object> data2 = new HashMap<String, Object>();
        HashMap<String, Object> map1 = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        map1.put("合同编号",contractSponsor.getContractSponsorNo());
        map1.put("合同名称",contractSponsor.getName());
        map1.put("提交日期", DateUtils.getDate());
        map1.put("客户名称",contractSponsor.getLesseeName());
        map1.put("租赁开始日期", sdf.format(contractSponsor.getRentStateTime()));
        map1.put("租赁结束日期",sdf.format(contractSponsor.getRentEndTime()));
        map1.put("押金金额",contractSponsor.getCashPledge());
        map1.put("单据ID",contractSponsor.getId());
        //发起人
        Object id = getLoginId(contractSponsor.getToken(), contractSponsor.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0028", map1);

        data1.put("data", data2);

        map.put("data", data1);

        JSONObject object = new JSONObject(map);
        System.out.println(object);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }


    /**
     * 押金退款提交审批
     * @param contractSponsor 合同发起
     * @return
     */
    @Override
    public String oaDepositRefund(ContractSponsor contractSponsor) throws IOException {
        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+contractSponsor.getToken();
        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");

        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "YJTKSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");

        Map<String, Object> data2 = new HashMap<String, Object>();
        HashMap<String, Object> map1 = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        map1.put("合同编号",contractSponsor.getContractSponsorNo());
        map1.put("合同名称",contractSponsor.getName());
        map1.put("提交日期", DateUtils.getDate());
        map1.put("客户名称",contractSponsor.getLesseeName());
        map1.put("租赁开始日期", sdf.format(contractSponsor.getRentStateTime()));
        map1.put("租赁结束日期",sdf.format(contractSponsor.getRentEndTime()));
        map1.put("押金金额",contractSponsor.getCashPledge());
        map1.put("单据ID",contractSponsor.getId());
        //发起人
        Object id = getLoginId(contractSponsor.getToken(), contractSponsor.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0028", map1);

        data1.put("data", data2);

        map.put("data", data1);

        JSONObject object = new JSONObject(map);
        System.out.println(object);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }

    /**
     * 维修项目提交审批
     * @param maintenanceApply
     * @return
     * @throws IOException
     */
    @Autowired
    private AssetMapper assetMapper;
    @Override
    public String oaMaintenanceApply(MaintenanceApply maintenanceApply) throws IOException {
        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+maintenanceApply.getToken();
        Asset asset = assetMapper.selectAssetById(maintenanceApply.getAssetId());
        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");

        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "WXXMSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");

        Map<String, Object> data2 = new HashMap<String, Object>();
        HashMap<String, Object> map1 = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        map1.put("上传图片",maintenanceApply.getMaintenancePic());
        map1.put("上报描述",maintenanceApply.getDescription());
        map1.put("时间", DateUtils.getDate());
        map1.put("承租人",maintenanceApply.getTenantryName());
        map1.put("房产名称", maintenanceApply.getAssetName());
        map1.put("房屋地址",asset.getAddress());
        map1.put("面积",asset.getPropertyArea().toPlainString());
        map1.put("单据ID",maintenanceApply.getId());
        //发起人
        Object id = getLoginId(maintenanceApply.getToken(), maintenanceApply.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0031", map1);

        data1.put("data", data2);

        map.put("data", data1);

        JSONObject object = new JSONObject(map);
        System.out.println(object);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }

    /**
     * 建设项目提交审批
     * @param constructionApply
     * @return
     */
    @Autowired
    private ConstructionEnclosureMapper constructionEnclosureMapper;
    @Override
    public String oaConstructionApply(ConstructionApply constructionApply) throws Exception {
        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+constructionApply.getToken();
        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");
        HashMap<String, Object> map1 = new HashMap<>();
        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "JSXMSPSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        ConstructionEnclosure enclosure = new ConstructionEnclosure();
        enclosure.setConstructionApplyId(constructionApply.getId());
        List<ConstructionEnclosure> enclosureList = constructionEnclosureMapper.selectConstructionEnclosureList(enclosure);
        if (StringUtils.isNotEmpty(enclosureList)){
            long l = new Random().nextLong();
            for (int i = 0;enclosureList.size()-1>=i;i++){
                //合同文本
                Map<String, Object> map3 = new HashMap<>();
                map3.put("fileUrl",getOaFile(enclosureList.get(i).getUrl(),constructionApply.getToken()));
                map3.put("sort",i+1);
                map3.put("subReference",l);
                list.add(map3);
            }
            map1.put("项目情况附件",l);
        }

        Map<String, Object> data2 = new HashMap<String, Object>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        map1.put("项目名称",constructionApply.getName());
        map1.put("发起人时间", DateUtils.getDate());
        map1.put("项目情况",constructionApply.getDescription());
        map1.put("预算金额",constructionApply.getBudgetAmount());
        map1.put("单据ID",constructionApply.getId());

        //发起人
        Object id = getLoginId(constructionApply.getToken(), constructionApply.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0033", map1);
        data2.put("thirdAttachments",list);
        data1.put("data", data2);

        map.put("data", data1);

        JSONObject object = new JSONObject(map);
        System.out.println(object);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }

    /**
     * 项目验收提交审批
     * @param projectAcceptance 项目验收
     * @return
     */
    @Override
    public String oaProjectAcceptance(ProjectAcceptance projectAcceptance) throws IOException {
        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+projectAcceptance.getToken();

        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");

        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "XMYSSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");

        Map<String, Object> data2 = new HashMap<String, Object>();
        HashMap<String, Object> map1 = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        map1.put("审核单号",projectAcceptance.getContractNo());
        map1.put("项目名称",projectAcceptance.getName());
        map1.put("提交日期", DateUtils.getDate());
        map1.put("合同开工日期", sdf.format(projectAcceptance.getStartAt()));
        map1.put("合同竣工日期",sdf.format(projectAcceptance.getEndAt()));
        map1.put("合同总费用",projectAcceptance.getTotalAmount());
        map1.put("单据ID",projectAcceptance.getId());
        //发起人
        Object id = getLoginId(projectAcceptance.getToken(), projectAcceptance.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0036", map1);

        data1.put("data", data2);

        map.put("data", data1);

        JSONObject object = new JSONObject(map);
        System.out.println(object);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }

    /**
     * 合同申请提交审批
     * @param contract 合同申请
     * @return
     */
    @Autowired
    private ContractEnclosureMapper contractEnclosureMapper;
    @Override
    public String oaContract(Contract contract) throws Exception {
        String url = "http://www.ntgrzc.com/seeyon/rest/bpm/process/start?token="+contract.getToken();
        //获取合同发起参数，对应OA
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appName", "collaboration");
        HashMap<String, Object> map1 = new HashMap<>();
        Map<String, Object> data1 = new HashMap<String, Object>();
        //OA默认数据源
        data1.put("templateCode", "JSXMSPSPD");
        data1.put("draft", "0");
        data1.put("attachments", new ArrayList<Long>());
        data1.put("relateDoc", "");
        data1.put("subject", "");
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        ContractEnclosure contractEnclosure = new ContractEnclosure();
        contractEnclosure.setContractApplyId(contract.getId());
        List<ContractEnclosure> enclosureList = contractEnclosureMapper.selectContractEnclosureList(contractEnclosure);
        if (StringUtils.isNotEmpty(enclosureList)){
            long l = new Random().nextLong();
            for (int i = 0;enclosureList.size()-1>=i;i++){
                //合同文本
                Map<String, Object> map3 = new HashMap<>();
                map3.put("fileUrl",getOaFile(enclosureList.get(i).getUrl(),contract.getToken()));
                map3.put("sort",i+1);
                map3.put("subReference",l);
                list.add(map3);
            }
            map1.put("合同文本",l);
        }

        Map<String, Object> data2 = new HashMap<String, Object>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        map1.put("甲方",contract.getFirstPartyName());
        map1.put("乙方",contract.getSecondPartyName());
        map1.put("发起人时间", DateUtils.getDate());
        map1.put("审批单号",contract.getContractNo());
        map1.put("项目名称",contract.getName());
        map1.put("单据ID",contract.getId());

        //发起人
        Object id = getLoginId(contract.getToken(), contract.getLoginName());
        map1.put("发起人",id);//发起人
        data2.put("formmain_0037", map1);
        data2.put("thirdAttachments",list);
        data1.put("data", data2);

        map.put("data", data1);

        JSONObject object = new JSONObject(map);
        System.out.println(object);

        Response response = null;
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(url).method("POST", body)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)").
                addHeader("Content-Type", "application/json").build();
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body().string();
    }


    @Override
    public Object getLoginId(String token,String loginName) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        Object id = "";
        try{
            // 创建客户端连接对象
            httpClient = HttpClients.createDefault();
            String url = "http://www.ntgrzc.com/seeyon/rest/orgMember"+"?token="+token+"&loginName="+loginName;
            HttpGet get = new HttpGet(url);

            // 获取返回对象
            response = httpClient.execute(get);

            // 整理返回值
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"utf-8");
            JSONObject object = JSONObject.parseObject(result);
            id = object.get("id");
        }catch (Exception  e){
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
                response.close();
            }catch (IOException i){
                i.printStackTrace();
            }

        }

        return id;
    }


    /**
     * 获取OA流程详情
     * @param oaFile OA链接
     * @return
     */
    @Override
    public String getOaUrl(String oaFile,String loginName) throws UnsupportedEncodingException {
        //加密，根据当前登录人和时间戳
        String s1 = Base64.getEncoder().encodeToString((loginName + "," + new Date().getTime()).getBytes());
        String s = oaFile + "&ticket=" + s1;
        return s;
    }

    /**
     * 单点登录--OA
     * @param from 固定参数 ntgrZcSSO
     * @param loginName OA登录名
     * @return
     */
    @Override
    public String singleLogin(String from, String loginName) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        //
        String s1 = Base64.getEncoder().encodeToString((loginName + "," + new Date().getTime()).getBytes());
        try{
            // 创建客户端连接对象
            httpClient = HttpClients.createDefault();
            String url = "http://www.ntgrzc.com/seeyon/login/sso?from="+from+"&ticket="+s1;
            HttpGet get = new HttpGet(url);

            // 获取返回对象
            response = httpClient.execute(get);

            // 整理返回值
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"utf-8");
        }catch (Exception  e){
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
                response.close();
            }catch (IOException i){
                i.printStackTrace();
            }

        }

        return result;
    }

    /**
     *
     * @param page 页数
     * @param pageSize 每页显示数量
     * @param loginName OA登录名
     * @return
     */
    @Override
    public String backlog(Integer page, Integer pageSize, String loginName,String token) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try{
            // 创建客户端连接对象
            httpClient = HttpClients.createDefault();
            String url = "http://www.ntgrzc.com/seeyon/rest/ntgrAffairs/pending/loginName/"+loginName+"/"+page+"/"+pageSize+"?token="+token;
            System.out.println(url);
            HttpGet get = new HttpGet(url);

            // 获取返回对象
            response = httpClient.execute(get);

            // 整理返回值
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"utf-8");
        }catch (Exception  e){
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
                response.close();
            }catch (IOException i){
                i.printStackTrace();
            }

        }

        return result;
    }

    /**
     * 获取OA已办信息
     * @param page 页数
     * @param pageSize 每页显示数量
     * @param loginName OA登录名
     * @return
     */
    @Override
    public String replied(Integer page, Integer pageSize, String loginName, String token) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try{
            // 创建客户端连接对象
            httpClient = HttpClients.createDefault();
            String url = "http://www.ntgrzc.com/seeyon/rest/ntgrAffairs/done/loginName/"+loginName+"/"+page+"/"+pageSize+"?token="+token;
            HttpGet get = new HttpGet(url);
            // 获取返回对象
            response = httpClient.execute(get);

            // 整理返回值
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"utf-8");
        }catch (Exception  e){
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
                response.close();
            }catch (IOException i){
                i.printStackTrace();
            }

        }

        return result;
    }


    /**
     * 文件上传
     */
    private Object getOaFile(String address,String token) throws Exception {
        File file = getNetUrlHttp(address);
//        File file = getFile(address);
//        File file = null;
//        MultipartFile file1 = createMultipartFile(address);
        String url = "http://www.ntgrzc.com/seeyon/rest/attachment?token="+token;
//        file = multipartFileToFile(file);
        String path = file.getAbsolutePath();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MultipartBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("imagefile", FileToMultipartFile(file).getOriginalFilename(),
                        okhttp3.RequestBody.create(okhttp3.MediaType.parse("image/*"),
                                new File(path)))
                .addFormDataPart("serialnum", "1")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("POST", (okhttp3.RequestBody) body)
                .addHeader("Content-Type", "multipart/form-data")
                .build();
        Response response = client.newCall(request).execute();

//        System.out.println(JSONObject.parseObject(response.body().string()));
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        List<Map<String, Object>> list=(List<Map<String, Object>>)jsonObject.get("atts");
        return list.get(0).get("fileUrl");
    }




    public MultipartFile FileToMultipartFile(File oneFile) throws IOException
    {
        FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(oneFile.toPath()), false, oneFile.getName(), (int) oneFile.length(), oneFile.getParentFile());
        InputStream input = null;
        OutputStream os = null;
        MultipartFile multipartFile = null;
        try {
            input = new FileInputStream(oneFile);
            os = fileItem.getOutputStream();
            IOUtils.copy(input, os);
            multipartFile = new CommonsMultipartFile(fileItem);
            input.close();
            os.close();
            return multipartFile;
        } catch (IOException ex) {
            throw new RuntimeException();
        } finally {
            if(input != null){
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static File getFile(String url) throws Exception {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."));
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return file;
    }
    private File getNetUrlHttp(String path) throws UnsupportedEncodingException {
        //对本地文件命名，path是http的完整路径，主要得到资源的名字

        String newUrl = tranformStyle(path);
        newUrl = newUrl.split("[?]")[0];
        String[] bb = newUrl.split("/");
        //得到最后一个分隔符后的名字
        String fileName = bb[bb.length - 1];
        //保存到本地的路径
        String filePath="d:\\audio\\"+fileName;
        File file = null;

        URL urlfile;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            //判断文件的父级目录是否存在，不存在则创建
            file = new File(filePath);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            try{
                //创建文件
                file.createNewFile();
            }catch (Exception e){
                e.printStackTrace();
            }
            //下载
            urlfile = new URL(newUrl);
            inputStream = urlfile.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 对中文字符进行UTF-8编码
     * @param source 要转义的字符串
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String tranformStyle(String source) throws UnsupportedEncodingException
    {
        char[] arr = source.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < arr.length; i++)
        {
            char temp = arr[i];
            if(isChinese(temp))
            {
                sb.append(URLEncoder.encode("" + temp, "UTF-8"));
                continue;
            }
            sb.append(arr[i]);
        }
        return sb.toString();
    }

    /**
     * 获取字符的编码值
     * @param s
     * @return
     * @throws UnsupportedEncodingException
     */
    public static int getValue(char s) throws UnsupportedEncodingException
    {
        String temp = (URLEncoder.encode("" + s, "GBK")).replace("%", "");
        if(temp.equals(s + ""))
        {
            return 0;
        }
        char[] arr = temp.toCharArray();
        int total = 0;
        for(int i = 0; i < arr.length; i++)
        {
            try
            {
                int t = Integer.parseInt((arr[i] + ""), 16);
                total = total * 16 + t;
            }
            catch(NumberFormatException e)
            {
                e.printStackTrace();
                return 0;
            }
        }
        return total;
    }

    /**
     * 判断是不是中文字符
     * @param c
     * @return
     */
    public static boolean isChinese(char c)
    {

        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);

        if(ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS

                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS

                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A

                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION

                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION

                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS)
        {

            return true;

        }

        return false;

    }


}
